#!/usr/bin/python
#TiVoToDo.py

import logging
import sys

import config as c
import parsers as p
import reports as rpt
import request as req
import tools as t

# Create a current runtime date object.
t.run_time()

# Set up logging
c.init_logging()
log = logging.getLogger('TiVoToDo')
if c.get_debug():
    log.setLevel(logging.DEBUG)

# Record python version in debug.log.
log.debug('python version: %s' % sys.version.split(None, 1)[0])

# Find out if there's anything to do.
if all(['None' in c.display_list, 'None' in c.csv_list]):
    log.error('\nNothing to do!\n' +
              '\nPlease specify at least one report type in either:\n' +
              '"csv" or "display" options in TiVoToDo.conf.\n')
    x = raw_input("Press Enter to exit")
    sys.exit (1)

# Find TiVos on the LAN
b = t.Beacon()
b.start()
b.stop()

# Include any TiVo.
for tivo, tsn in c.get_incl().items():
    c.tivos[tivo] = tsn
    log.info('Including TiVo: "%s" (tsn %s)' % (tivo, tsn))

# Exclude any specified TiVos from the list.
excl_tivos = c.get_excl()
if excl_tivos:
    for i in range(len(excl_tivos)):
        if excl_tivos[i] in c.tivos:
            log.info('Excluding TiVo: "%s"' % excl_tivos[i])
            del c.tivos[excl_tivos[i]]

# Assess the number of TiVos found on the LAN
if len(c.tivos) < c.get_tivo_count():
    log.error('\nThe minimum number of TiVos: %s, ' % c.get_tivo_count() +
              'were not found on the network.'
              '\nPlease try again.\n')
    if c.get_output('display'):
        x = raw_input("Press Enter to exit")
    sys.exit (1)

# Login to tivo.com
parser  = p.IndxParser()
log.info('\nLogging in...')
url, login_data = t.login(c.base_url, c.indx_url,
                          c.get_email(), c.get_password())
req.request_url(url, parser, login_data)

if c.get_beta():
    url, login_data = t.login(c.beta_url, c.indx_url,
                              c.get_email(), c.get_password())
    req.request_url(url, parser, login_data)

# Gather Channel Lineups.
if any(['Channel' in c.csv_list, 'Channel' in c.display_list,
        'All' in c.csv_list, 'All' in c.display_list]):
    for tivo, tsn in c.tivos.iteritems():
        log.info('\nWorking on Channel Lineups for %s' % tivo)
        c.tivo_clu = [['TiVo name', 'Channel number', 'Channel name']]
        c.rdi_tivo = tivo
        c.rdi_ttsn = tsn
        url = c.base_url + c.indx_url + '?tsn=' + tsn
        login_data = None
        req.request_url(url, parser, login_data)
        if any(['Channel' in c.csv_list, 'All' in c.csv_list]):
            t.make_csv(c.tivo_clu, 'Channel.Lineup.%s.csv' % tivo)
        if any(['Channel' in c.display_list, 'All' in c.display_list]):
            for row in range(len(c.tivo_clu)):
                log.info('%s %s %s' % (c.tivo_clu[row][0].center(16),
                                       c.tivo_clu[row][1].center(16),
                                       c.tivo_clu[row][2].center(16)))
            x = raw_input("\nViewing Channel Lineup for " +
                          "%s. Press Enter to continue\n" % tivo)


# Gather the ToDo list for all the TiVos listed.
parser  = p.ToDoParser()

# Load a shows cache file if present.
t.read_cache()

for tivo, tsn in c.tivos.iteritems():
    log.info('\nWorking on To Do List for %s\n' % tivo)
    c.noShows = False
    c.rdi_tivo = tivo
    c.rdi_ttsn = tsn
    offset = 0

    while not c.noShows:
        url = c.base_url + c.todo_url + '&tsn=' + tsn + '&offset=%d' % offset
        offset += 20
        login_data = None
        req.request_url(url, parser, login_data)
        if not c.noShows:
            log.info('\nDone with To Do List page %d\n' % (offset/20))

if c.get_beta():
    for tivo, tsn in c.tivos.iteritems():
        log.info('\nWorking on To Do List for %s\n' % tivo)
        c.noShows = False
        c.rdi_tivo = tivo
        c.rdi_ttsn = tsn
        offset = 0

        while not c.noShows:
            url = c.beta_url + c.todo_url + '&tsn=' + tsn + '&offset=%d' % offset
            offset += 20
            login_data = None
            req.request_url(url, parser, login_data)
            if not c.noShows:
                log.info('\nDone with To Do List page %d\n' % (offset/20))

log.info('Done searching')

# Create a Raw Data List object.
t.dump_object(c.rdl, 'rdl.obj')

# Create any reports from the gathered information.

# ToDo.By.Date
if any(['Date' in c.csv_list, 'Date' in c.display_list,
        'All' in c.csv_list, 'All' in c.display_list]):
    rpt.date_report(0, (5, 10), 'ToDo.By.Date.csv', 'Date')

# ToDo.By.TiVo
if any(['Tivo' in c.csv_list, 'Tivo' in c.display_list,
        'All' in c.csv_list, 'All' in c.display_list]):
    rpt.date_report(10, (10, 5), 'ToDo.By.TiVo.csv', 'Tivo')

# ToDo.By.Show
if any(['Show' in c.csv_list, 'Show' in c.display_list,
        'All' in c.csv_list, 'All' in c.display_list]):
    rpt.show_report()

# ToDo.By.Date
if any(['Tuner' in c.csv_list, 'Tuner' in c.display_list,
        'All' in c.csv_list, 'All' in c.display_list]):
    rpt.tuner_report()

if 'None' not in c.csv_list:    
    log.info('\nPlease check ' + str(c.output_dir) + ' for the output.\n')

if 'None' not in c.display_list:    
    x = raw_input("\nDone! Press Enter to exit")
    exit()
